package cc.facesign.admin.controller;

import cc.facesign.admin.bean.TblConf;
import cc.facesign.admin.bean.TblConfUser;
import cc.facesign.admin.bean.vo.UserVo;
import cc.facesign.admin.bean.xls.AddConfUserXls;
import cc.facesign.admin.bean.xls.AddDeptUserXls;
import cc.facesign.admin.service.TblConfService;
import cc.facesign.admin.service.TblConfUserService;
import cc.facesign.admin.service.TblUserService;
import cc.facesign.admin.service.impl.XlsServiceImpl;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.admin.utils.RedisKey;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.R;
import cc.facesign.servicebase.utils.RedisCache;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(description = "xls操作")
@RestController
@RequestMapping("/admin/xls")
public class XlsController {

    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private XlsServiceImpl xlsService;

    @Autowired
    private TblConfUserService confUserService;

    @Autowired
    private TblUserService userService;

    @Autowired
    private TblConfController confController;

    @Autowired
    private TblConfService confService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 向部门中添加用户，返回不符合以下要求的用户信息（err）
     * 要求：
     * 1、图片格式必须是 身份证号.jpg
     * 2、xls中用户的所有信息都不能为空
     * 3、每个用户只接受一张图片
     *
     * @param deptId 部门id
     * @return 有问题的用户信息
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe')")
    @ApiOperation("向部门中添加用户")
    @PostMapping("/addUserForDept/{deptId}")
    public R addUser(@PathVariable("deptId") String deptId,
                     MultipartFile xls,
                     List<MultipartFile> file) {

        if (!powerUtils.getCurrentChildDeptIdSet().contains(deptId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        List<AddDeptUserXls> errs = xlsService.addUserForDept(deptId, xls, file);

        List<Object> successList = redisCache.getCacheList(RedisKey.XLS_UPLOAD_DEPT_USER_SUCCESS + powerUtils.getId());
        redisCache.deleteObject(RedisKey.XLS_UPLOAD_DEPT_USER_SUCCESS + powerUtils.getId());

        return R.ok().data("errs", errs).data("success", successList);
    }

    /**
     * 向会议中添加用户，返回不符合以下要求的用户信息（err）
     * 要求：
     * 1、所在部门的上级不能通过该方法添加进会议
     * 2、操作者所能管理的部门中，需存在该用户
     * 3、cardId需与姓名匹配
     *
     * @param confId 会议id
     * @param file   xls文件
     * @return 有问题的用户信息
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("向会议中添加用户")
    @PostMapping("/addUserForConf/{confId}")
    public R addUserForConf(@PathVariable("confId") String confId,
                            MultipartFile file) {
        if (!powerUtils.getCurrentChildConfIdSet().contains(confId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        List<AddConfUserXls> err = xlsService.addUserForConf(file, confId);
        // 更新conf表人数
        confService.updateTotal(confId);

        List<TblConfUser> list = redisCache.getCacheList(RedisKey.XLS_UPLOAD_CONF_USER_SUCCESS + powerUtils.getId());
        redisCache.deleteObject(RedisKey.XLS_UPLOAD_CONF_USER_SUCCESS + powerUtils.getId());

        List<String> userIds = new ArrayList<>();
        userIds = list.stream()
                .map(x -> x.getUserId())
                .collect(Collectors.toList());

        return R.ok().data("err", err)
                .data("successUserIds", userIds);
    }


    /**
     * 可执行该操作的：
     * 拥有conf所在部门的管理员权限、或为会议创始人
     * map中有效参数为：
     * status： 签到状态“0”、“1”
     * deptId： 父部门id（查的时候包括子部门）
     * name： 用户名模糊查询
     *
     * @param response
     * @param confId
     * @return
     * @throws IOException
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("导出会议中的用户数据")
    @PostMapping("/exportUserForConf")
    public R exportUserForConf(HttpServletResponse response, String confId,
                               @RequestBody(required = false) Map<String, String> map) throws IOException {

        TblConf conf = confService.getById(confId);
        response.setContentType("text/html;charset=UTF-8;");
        response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + conf.getCode() + "-users");

        IPage<UserVo> page = (IPage<UserVo>) confController.getUserListById(confId, 1, 0x3f3f3f3f, map)
                .getData().get("page");
        List<UserVo> records = page.getRecords();

        xlsService.exportUserForConf(response, records);

        return R.ok();
    }
}
